<?php

namespace app\api\service;

use api\AES;
use app\model\OilStore;

class OilStoreService extends CommonService
{
    public $uniqId = '';

    /**
     * 从小桔方拉取加油站列表.
     */
    public function getStoreFromApi($supplierInfo)
    {
        ignore_user_abort(true);
        set_time_limit(0);

        // 各个供应商sdk处理
        switch ($supplierInfo['alias']) {
            case OIL_SUPPLIER_ALIAS['xiaoju']['alias']: // 小桔供应商
                invoke(OilXiaojuService::class)->getStore($supplierInfo->id);
            break;
        }

        return $this->valiReturn([]);
    }

    /*
     获取列表
    */
    public function getOilStoreList($where, $paginate, $sort, $locat = [], $field = '*')
    {
        $whereArr = [];
        if ($where['brand_name']) {
            $whereArr[] = ['brand_name', '=', $where['brand_name']];
        }
        if ($where['store_name']) {
            $whereArr[] = ['store_name', 'like', '%'.$where['store_name'].'%'];
        }

        if ($locat) {
            $distance = "ROUND(6378.138*2*ASIN(SQRT(POW(SIN(({$locat['lat']}*PI()/180-lat*PI()/180)/2),2)+COS({$locat['lat']}*PI()/180)*COS(lat*PI()/180)*POW(SIN(({$locat['lon']}*PI()/180-lon*PI()/180)/2),2)))*1000) AS distance";
        } else {
            $distance = '';
        }

        $res = OilStore::hasWhere('item', function ($query) use ($where) {
            $query->where('item_name', $where['item_name'])->whereNull('deleted_at');
        })
        ->with(['item' => function ($query) use ($where) {
            $query->where('item_name', $where['item_name']);
        }])->fieldRaw($distance)
        ->where($whereArr)
        ->order($sort)
        ->paginate($paginate);

        if (!$res->isEmpty()) {
            $res = $res->toArray();
        } else {
            $res = [];
        }

        return $this->valiReturn($res);
    }

    /*  转成数据库字段 */
    protected function transferData($data, $supplierId)
    {
        $result = [];
        if (!$data) {
            return $result;
        }

        foreach ($data as $k => $v) {
            foreach ($v as $k2 => $v2) {
                $tempV[uncamelize($k2)] = is_array($v2) ? json_encode($v2, JSON_UNESCAPED_UNICODE) : $v2; // 下一级数组保存成json 且不转成下划线格式
            }
            $tempV['supplier_id'] = $supplierId;
            $tempV['batch_id'] = $this->uniqId;
            //$tempV['created_at'] = $datetime;
            //$tempV['updated_at'] = $datetime;
            //$tempV['step'] = 0;
            // 处理
            foreach ($tempV as $k2 => $v2) {
                $keysArr = [
                    'supplier_id',
                    'store_id',
                    'store_name',
                    'store_logo',
                    'city_name',
                    'province_name',
                    'address',
                    'lon',
                    'lat',
                    'brand_name',
                    'hui_labels',
                    'item_info_list',
                    'business_hours_start',
                    'business_hours_end',
                    'batch_id',
                ];

                if (!in_array($k2, $keysArr)) {
                    unset($tempV[$k2]);
                }

                $tempV['brand_name'] = $tempV['brand_name'] ?? '';  // 返回值没有 brand_name 情况
            }

            $result[] = $tempV;
        }

        return  $result;
    }

    public function makeH5Url($cnid, $platform = AGENT_USER_PLATFORM, $version = '1.0.0')
    {
        $token = base64_encode(AES::encrypt(json_encode(['platform' => $platform, 'cnid' => $cnid, 'v' => $version]), 'glQ8vbPrxWD8LA0Y'));

        return $this->valiReturn(['h5' => app()->env['XIAOJU_OIL_H5_DOMAIN'].'/oil/?v='.$version.'&cipher='.$token.'&cnid='.$cnid]);
    }

    public function decryptH5Token($token, $version, $cnid = 0)
    {
        if (!$token || !$version || !$cnid) {
            return $this->inValiReturn('参数异常'.__LINE__);
        }
        if ('1.0.0' == $version) { //采用AES解密token
            $decryptInfo = json_decode(AES::decrypt(base64_decode($token), 'glQ8vbPrxWD8LA0Y'), true);
            /* var_dump($decryptInfo);
            exit; */
            if (!is_array($decryptInfo)) {
                return $this->inValiReturn('参数异常'.__LINE__);
            }

            if (empty($decryptInfo['cnid'])) {
                return $this->inValiReturn('参数异常'.__LINE__);
            }
            if (empty($decryptInfo['platform'])) {
                return $this->inValiReturn('参数异常'.__LINE__);
            }
            if (empty($decryptInfo['v'])) {
                return $this->inValiReturn('参数异常'.__LINE__);
            }
            if ($decryptInfo['v'] != $version) {
                return $this->inValiReturn('参数异常'.__LINE__);
            }
            doLog($cnid.json_encode($decryptInfo, JSON_UNESCAPED_UNICODE));

            if ($cnid && $cnid != $decryptInfo['cnid']) {
                return $this->inValiReturn('非法参数'.__LINE__);
            }
        } else {
            return $this->inValiReturn('非法参数'.__LINE__);
        }

        return $this->valiReturn($decryptInfo);
    }
}
